package ran.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ran.entity.PageRequest;
import ran.entity.QuestionInfo;
import ran.entity.ResponseResult;
import ran.service.QuestionService;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-09-30
 * Time: 12:46
 */
@RestController
@RequestMapping("/api/questions")
@RequiredArgsConstructor
@Slf4j
public class QuestionController {
    @Autowired
    private QuestionService questionService;

    /**
     * Excel 文件上传并导入数据库
     * @param file 前端上传的 Excel 文件 (MultipartFile)
     */
    @RequestMapping("/import")
    public ResponseEntity<String> importQuestions(@RequestParam("file") MultipartFile file) {
        try {
            questionService.importFromExcel(file);
            return ResponseEntity.ok("✅ 导入成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("❌ 导入失败: " + e.getMessage());
        }
    }

    @RequestMapping("/getListByPage")
    public ResponseResult<QuestionInfo> getListByPage(PageRequest pageRequest) {
        return questionService.getListByPage(pageRequest);
    }



    // 更新图书
    // 1. 先查看对应id的图书
    @RequestMapping("/queryQuestionById")
    public QuestionInfo queryBookById(Integer questionId) {
        log.info("查询图书信息,bookId: " +questionId);
        return questionService.queryQuestionById(questionId);
    }


    @RequestMapping("/updateQuestion")
    public boolean updateBook(QuestionInfo questionInfo) {
        log.info("修改试题, questionInfo: {}",questionInfo);
        try {
            // 成功
            return questionService.updateBook(questionInfo);
        }catch (Exception e) {
            log.error("修改图书异常,e: " ,e);
            return false;
        }
    }

    @RequestMapping("/deleteQuestion")
    public boolean deleteQuestion(Long questionId) {
        log.info("删除试题, boookId: " + questionId);
        try {
            // 成功
            return questionService.deleteQuestion(questionId);
        }catch (Exception e) {
            log.error("删除图书异常,e: " ,e);
            return false;
        }
    }

    @RequestMapping("/deleteBatch")
    public boolean deleteBatch(@RequestParam List<Integer> ids) {
        log.info("批量删除试题, ids: {}",ids);
        try {
            questionService.deleteBatch(ids);
            return true;
        }catch (Exception e) {
            log.error("批量删除失败,e: ",e);
            return false;
        }
    }
}
